﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
///BookManger 书籍管理类
/// </summary>
public class BookManger
{
	public BookManger()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}
    /// <summary>
    /// 书架中删除书籍
    /// </summary>
    /// <param name="sUserName">用户名</param>
    /// <param name="sBookID">书籍ID</param>
    /// <returns>删除的条数</returns>
    public static int deleteBook(string sUserName, string sBookID)
    {
        SqlDataSource ds = new SqlDataSource();
        string[] sBooks = sBookID.Split('_');
        int iBookCount = sBooks.Length;
        int iRowEffect = 0;
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.DeleteCommand = "delete from ls_MyBook where MyBook_BookID=@bookid and  MyBook_UserName=@username";
        for (int i = 0; i < iBookCount; i++)
        {
            ds.DeleteParameters.Clear();
            ds.DeleteParameters.Add("username", sUserName);
            ds.DeleteParameters.Add("bookid", sBooks[i]);
            iRowEffect = ds.Delete();
        }
        ds.Dispose();

        return iRowEffect;
    }
    /// <summary>
    /// 用户添加书籍到书架
    /// </summary>
    /// <param name="sUserName">用户名</param>
    /// <param name="sBookID">书号</param>
    /// <returns>添加条数</returns>
    public static int addBook(string sUserName, string sBookID)
    {
        SqlDataSource ds = new SqlDataSource();
        string[] sBooks = sBookID.Split('_');
        int iBookCount=sBooks.Length;
        int iRowEffect=0;
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.InsertCommand = "insert into ls_MyBook(MyBook_UserName,MyBook_BookID) select @username,@bookid where not exists (select * from ls_MyBook where MyBook_UserName=@username and MyBook_BookID=@bookid) ";
        for (int i = 0; i < iBookCount; i++)
        {
            ds.InsertParameters.Clear();
            ds.InsertParameters.Add("username", sUserName);
            ds.InsertParameters.Add("bookid", sBooks[i]);
            iRowEffect += ds.Insert();
        }
        ds.Dispose();
        return iRowEffect;
    }
    /// <summary>
    /// 增加新书
    /// </summary>
    /// <param name="bookinfo">Book信息类</param>
    /// <returns>新增的记录条数。</returns>
    public static int newBook(Book bookinfo,string sUserName)
    {
        int iRowEffect;
        //新插入的记录号。
        int iRowID=0;
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.InsertCommand = "insert into ls_Book(Book_Name,Book_Writer,Book_Cover,Book_Rem,Book_Type,Book_UserName)  ";
        ds.InsertCommand+= " select @bookname,@writer,@cover,@rem,@type,@username  where not exists (select * from ls_Book where Book_Name=@bookname)";
        ds.InsertParameters.Add("bookname", bookinfo.BookName);
        ds.InsertParameters.Add("writer", bookinfo.BookWriter);
        ds.InsertParameters.Add("cover", bookinfo.BookCover);
        ds.InsertParameters.Add("rem", bookinfo.BookRem);
        ds.InsertParameters.Add("type",TypeCode.Int32, bookinfo.BookType);
        ds.InsertParameters.Add("username",sUserName);
        iRowEffect=ds.Insert();

        if (iRowEffect != 0)
        {
            ds.SelectCommand = "select Max(Book_ID) bookid from ls_Book";
            DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
            iRowID = Convert.ToInt32(dv[0]["bookid"].ToString());
        }
            return iRowID;
            
    }
    /// <summary>
    /// 访问书籍时候增加1
    /// </summary>
    /// <param name="sBookID"></param>
    /// <returns>更新条数</returns>
    public static int visitBook(string sBookID)
    {
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.UpdateCommand = "update ls_Book set Book_WeekVisit=Book_WeekVisit+1,Book_TotalVisit=Book_TotalVisit+1 where Book_ID=@bookid ";
        ds.UpdateParameters.Add("bookid", sBookID);
        int iRowEffect=ds.Update();
        ds.Dispose();
        return iRowEffect;
    }
    /// <summary>
    /// 书籍中增加目录
    /// </summary>
    /// <param name="sBookID">书籍ID</param>
    /// <param name="sSiteList">目录字符串</param>
    /// <param name="sUserName">贡献者</param>
    /// <returns>,BookID_地址|用户名 格式放回</returns>
    public static string addBookList(string sBookID, string sSiteList,string sUserName)
    {
        string[] sList = sSiteList.Split('_');
        int iRowEffect = 0;
        string sReturn="";
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();

        ds.InsertCommand = "insert into ls_List(List_BookName,List_SiteName,List_BookID,List_SiteID,List_URL,List_Reg,List_UserName) ";
        ds.InsertCommand += "select Book_Name,Site_Name,Book_ID,Site_ID,@list,Site_ListReg,@username from ls_Book,ls_Site  ";
        ds.InsertCommand += "where  Book_ID=@bookid and Site_ID=@siteid and not exists (select * from ls_List where List_URL=@list)";

        for (int i = 0; i < sList.Length; i++)
        {
            ds.InsertParameters.Clear();
            string[] s=sList[i].Split('|');
            ds.InsertParameters.Add("siteid", s[0]);
            ds.InsertParameters.Add("list", s[1]);
            ds.InsertParameters.Add("username", sUserName);
            ds.InsertParameters.Add("bookid", sBookID);
            iRowEffect=ds.Insert();
            if (iRowEffect == 1)
                sReturn += "," +s[0]+"_"+ s[1];
        }
        ds.Dispose();
        if (sReturn != "")
        {
            //去掉最前面的,号
            sReturn = sReturn.Substring(1, sReturn.Length - 1);
            sReturn = sReturn + "|" + sUserName;
        }

        return sReturn;
    }
    /// <summary>
    /// 检测书籍是否存在
    /// </summary>
    /// <param name="sBookName">书籍名称</param>
    /// <returns>存在还是不存在</returns>
    public static bool checkBook(string sBookName)
    {
        bool bExists=false;
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select count(*) as amount from ls_Book where Book_Name=@bookname";
        ds.SelectParameters.Add("bookname", sBookName);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if ((int)dv[0]["amount"] > 0)
            bExists = true;
        return bExists;
    }
    /// <summary>
    /// 检测目录是否存在
    /// </summary>
    /// <param name="sListURL">目录地址URL</param>
    /// <returns>存在还是不存在</returns>
    public static bool checkList(string sListURL)
    {
        bool bExists = false;
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.SelectCommand = "select count(*) as amount from ls_List where List_URL=@listurl";
        ds.SelectParameters.Add("listurl", sListURL);
        DataView dv = (DataView)ds.Select(DataSourceSelectArguments.Empty);
        if ((int)dv[0]["amount"] > 0)
            bExists = true;
        return bExists;
    }
    /// <summary>
    /// 改变书籍类型
    /// </summary>
    /// <param name="book">书籍类</param>
    /// <param name="sUserName">用户名</param>
    /// <returns></returns>
    public static bool changeType(Book book, string sUserName)
    {
        int iRowUpdate= 0;
        int iRowInsert = 0;
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        string sMaxChange = ConfigurationSettings.AppSettings["maxchange"].ToString();
        //看看最近是否有更新记录，检查今天是不是更新了30个了。
        ds.InsertCommand = "insert into ls_Operate(Operate_UserName,Operate_Type,Operate_BookID)  ";
        ds.InsertCommand +=" select @username,1,@bookid where not exists (select * from ls_Operate where Operate_BookID=@bookid and Operate_UserName=@username and Operate_Type=1 and datediff(d,Operate_DateTime,getdate())<1) ";
        ds.InsertCommand += " and not exists (SELECT Operate_UserName FROM ls_Operate where Operate_UserName=@username and Operate_Type=1  and datediff(d,Operate_DateTime,getdate())<1  GROUP BY Operate_UserName HAVING (COUNT(*) > "+sMaxChange+"))";
        ds.InsertParameters.Add("username", sUserName);
        ds.InsertParameters.Add("bookid", book.BookID);
        iRowInsert = ds.Insert();
        if (iRowInsert == 1)
        {
            //更新书籍类型
            ds.UpdateCommand = "update ls_Book set Book_Type=@booktype where Book_ID=@bookid";
            ds.UpdateParameters.Add("booktype", book.BookTypeID);
            ds.UpdateParameters.Add("bookid", book.BookID);
            iRowUpdate = ds.Update();
        }
        //添加更改记录

        ds.Dispose();

        //两个都成功才返回true
        if (iRowInsert == 1 && iRowUpdate == 1)
            return true;
        else
            return false;
    }
    /// <summary>
    /// 给书投票
    /// </summary>
    /// <param name="sBookID">书籍ID</param>
    /// <param name="sUserName">用户名</param>
    /// <returns></returns>
    public static bool ticketIt(string sBookID, string sUserName)
    {
        int iRowUpdate = 0;
        int iRowInsert = 0;
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        string sMaxTicket = ConfigurationSettings.AppSettings["maxticket"].ToString();
        //看看最近是否有更新记录，如果没有，就更新它。
        ds.InsertCommand = "insert into ls_Operate(Operate_UserName,Operate_Type,Operate_BookID)  ";
        ds.InsertCommand += " select @username,2,@bookid where not exists (select * from ls_Operate where Operate_BookID=@bookid and Operate_UserName=@username and Operate_Type=2 and datediff(d,Operate_DateTime,getdate())<1)";
        ds.InsertCommand += " and not exists (SELECT Operate_UserName FROM ls_Operate where Operate_UserName=@username and Operate_Type=2  and datediff(d,Operate_DateTime,getdate())<1  GROUP BY Operate_UserName HAVING (COUNT(*) > " + sMaxTicket + "))";
        ds.InsertParameters.Add("username", sUserName);
        ds.InsertParameters.Add("bookid", sBookID);
        iRowInsert = ds.Insert();
        if (iRowInsert == 1)
        {
            //更新书籍类型
            ds.UpdateCommand = "update ls_Book set Book_MonthTicket=Book_MonthTicket+1,Book_TotalTicket=Book_TotalTicket+1 where Book_ID=@bookid";
            ds.UpdateParameters.Add("bookid", sBookID);
            iRowUpdate = ds.Update();
        }
        //添加更改记录

        ds.Dispose();

        //两个都成功才返回true
        if (iRowInsert == 1 && iRowUpdate == 1)
            return true;
        else
            return false;
    }
}
